﻿using System;
using System.Text;
using System.Web.Mvc;
using EnetaMvc.ApplicationServices.Dto;

namespace EnetaMvc.Web.Extensions
{
    public class vCalActionResult : ActionResult
    {
        private readonly EventDto _event;

        public vCalActionResult(EventDto evt)
        {
            if (evt == null)
                throw new ArgumentNullException("evt");

            _event = evt;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var buffer = new StringBuilder(1000);

            buffer.AppendLine("BEGIN:VCALENDAR");
            buffer.AppendLine("VERSION:2.0");
            buffer.AppendLine("BEGIN:VEVENT");
            buffer.AppendLine(string.Format("DTSTART:{0}", _event.StartDate.Value.ToUniversalTime().ToString("yyyyMMdd'T'HHmmss")));
            buffer.AppendLine(string.Format("DTEND:{0}", _event.EndDate.Value.ToUniversalTime().ToString("yyyyMMdd'T'HHmmss")));
            buffer.AppendLine(string.Format("SUMMARY:{0}", _event.Title));
            buffer.AppendLine(string.Format("DESCRIPTION:{0}", _event.Body));
            buffer.AppendLine(string.Format("LOCATION:{0}", _event.VenueName));
            buffer.AppendLine(string.Format("UID:ENETA{0}\n{1}", _event.Id, _event.StartDate.Value.Ticks));
            buffer.AppendLine("END:VEVENT");
            buffer.AppendLine("END:VCALENDAR");

            context.HttpContext.Response.ContentType = "text/calendar";
            context.HttpContext.Response.AddHeader("Content-disposition", String.Format("attachment; filename={0}.ics", _event.Id));
            context.HttpContext.Response.Write(buffer.ToString());
        }
    }
}